#!/usr/bin/env python


siteid = 'KPNS'
outdir = '.'
export_flag = False
UTC_offset = 4 

def plot_current_blwinds(siteid,outdir,UTC_offset,export_flag):
    import matplotlib
    if export_flag:
        import os
        matplotlib.use('agg')
    import matplotlib.pyplot as plt
    import cPickle
    from datetime import datetime, timedelta

    matplotlib.rcParams['xtick.minor.pad'] = 15

    color_dict = {'GFS 18Z'    : 'midnightblue',
              'GFS 12Z' : 'blue',
              'GFS 06Z' : 'cornflowerblue',
              'GFS 00Z' : 'cyan',
              'NAM 12Z' : 'limegreen',
              'NAMM 18Z'    : 'darkgreen',
              'NAM 00Z' : 'palegreen',
              'NAMM 06Z'    : 'lime'}


    # Let's start by getting our times straight
    # Only interested in the 24-hour period we're forecasting for
    # with a lead-in time.  ftime is the actual times we're
    # forecasting between, ptime is the times we're plotting

    nowtime = datetime.now()
    stime = nowtime.replace(hour=6,minute=0,second=0,microsecond=0)
    stime = stime + timedelta(hours=24)
    print "HERE", stime.strftime('%Y%m%d%H')

    # this must change depending on UTC offset
    start_ftime_wind = stime + timedelta(hours=(UTC_offset-6))

    lead_time = timedelta(hours=18)
    fcst_window = timedelta(hours=24)
    end_ftime_wind = start_ftime_wind + timedelta(hours=24)

    start_ptime = stime - lead_time
    end_ptime = stime + timedelta(hours=30)





    # Try to load the file
    try:
        f = open('./site_data/%s_bl_winds.pickle' % siteid.upper(),'r')
        fdict = cPickle.load(f)
        f.close()
    except:
        print "Could not open bl_winds archvie file: %s_bl_winds.pickle" % siteid.upper()
        exit(1)
    # Make a figure
    plt.figure(figsize=(12,11))
    for model in fdict.keys():
        dates = fdict[model]['dates']
        top_winds = fdict[model]['top_wind']
        mean_winds = fdict[model]['mean_wind']
        # Only plot the model if it's from today
        if fdict[model]['model_init'].day == datetime.now().day:
            plt.plot(dates,top_winds,color=color_dict[model],linestyle='dashed',linewidth=2,label='%s MaxML' % model)
            plt.hold(True)
            plt.plot(dates,mean_winds,color=color_dict[model],linewidth=2,label='%s MeanML' % model)

    leg = plt.legend(loc=0,ncol=4,mode='expand',handletextpad=0)
    leg.get_frame().set_alpha(0.5)
    ltexts = leg.get_texts()
    plt.setp(ltexts,fontsize='small')
    
    # Now do lots of axis formatting
    ax = plt.gca()
    ax.xaxis.set_major_locator(matplotlib.dates.HourLocator(byhour=[0,3,6,9,12,15,18,21]))
    ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%HZ'))
    ax.xaxis.set_minor_locator(matplotlib.dates.DayLocator())
    ax.xaxis.set_minor_formatter(matplotlib.dates.DateFormatter('%h %d'))
    maxval = ax.get_ylim()[1]
    ax.set_ylim((0,maxval+3))
    ax.set_yticks(range(0,int(maxval+3)))

    plt.axvspan(matplotlib.dates.date2num(start_ptime),matplotlib.dates.date2num(start_ftime_wind),facecolor='0.8',alpha=0.40)
    plt.axvspan(matplotlib.dates.date2num(end_ftime_wind),matplotlib.dates.date2num(end_ptime),facecolor='0.8',alpha=0.40)

    # Reformat the date axis
    ax.set_xlim([matplotlib.dates.date2num(start_ptime),matplotlib.dates.date2num(end_ptime)])


    plt.grid()
    plt.title('Forecast Mixed-Layer Mean and Max Winds at %s' % siteid.upper())
    plt.ylabel('Wind speed (kts.)')
    if export_flag:
        plt.savefig('%s_blwinds.png' % (siteid.upper()),bbox_inches='tight')
        os.system('mv %s_blwinds.png %s/%s_blwinds.png' % (siteid.upper(), outdir, siteid.upper()))
    else:
        plt.show()


if __name__ == '__main__':
    plot_current_blwinds(siteid, outdir, UTC_offset, export_flag)

